//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package io.chance.receiverlei.db;

import io.chance.receiverlei.channel.MessageDecode;
import io.chance.receiverlei.datapacket.ModbusCRCUnit;
import io.chance.receiverlei.db.model.BdMoRt;
import io.chance.receiverlei.db.model.BdMoRtSingle;
import io.chance.receiverlei.schedule.FixDataJob;
import lrq.data.DataTable;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RedisDbExecute {
    private static ThreadLocal<SimpleDateFormat> defaultSf = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    private static ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();

    public static void main(String[] args) throws Exception {
//        String text = "3,1,20191212173629,3;4,1,20191212173639,3;6,1,20191212173649,3;5,1,20191212173813,3;";
        String text = "4,1,20191212002401,6223;6150,6145,20191212001201,6223;6147,6145,20191212002401,6223;6150,6145,20191212004300,3;";

        String siteId = "16";
        String sql = "select * from bd_mo_rt_single t where t.SITE_ID='" + siteId + "' order by t.DATATIME";


        String ss = String.format("%04d", Integer.valueOf(Integer.toBinaryString(Integer.valueOf("111"))));
//        device.setAIRSWITCH(Integer.valueOf(ss.charAt(1) + ""));
//        device.setSPDJD(Integer.valueOf(ss.charAt(2) + ""));
//        device.setSPD(Integer.valueOf(ss.charAt(3) + ""));

        DataTable dataTable = DbManager.getDbExecuter().executeQuery(sql);
        List<BdMoRt> moRts = new ArrayList<>(dataTable.getRecordCount());
        for (int j = 0; j < dataTable.getRecordCount(); j++) {
            Date date = dataTable.getDate(j, "DATATIME");
            Timestamp now = new Timestamp(date.getTime());
            if (date != null && now.getTime() - date.getTime() < 180000) {//更新时间小于3分钟的才算进实时
                BdMoRt bdMoRt = new BdMoRt().setID(UUID.randomUUID().toString()).setSITE_ID(siteId)
                    .setPARAMETER(dataTable.getString(j, "PARAMETER"))
                    .setVALUE(dataTable.getString(j, "VALUE"))
                    .setDATATIME(now).setCREATETIME(now);
                moRts.add(bdMoRt);
            }
        }
        new FixDataJob().transRt2DeviceKvAndInsert(moRts);

        BdMoRtSingle rt = new BdMoRtSingle().setID("b866c348-818a-4fbb-a1c6-e84c6591e8bd").setSITE_ID("666").setPARAMETER("light").setVALUE("6").setDATATIME(new Timestamp(System.currentTimeMillis()));
        rt.setTableName("BD_MO_RT");
        DbManager.getDbExecuter().Create(rt);

        System.out.println(new Date(MessageDecode.bytes2Long(MessageDecode.hexToBytes("51315d40"))));
        System.out.println(new Date(MessageDecode.bytes2Long(MessageDecode.hexToBytes("405d3151"))));
        byte[] bytes = {01, 04, 01, 01, 80, 49};
        System.out.println(ModbusCRCUnit.CRCCheck(bytes));
        RedisDbExecute.setString("haha:xixi1:hehe", "hello");
        RedisDbExecute.setString("haha:xixi2:hehe", "hello");
        RedisDbExecute.setString("haha:xixi3:hehe", "hello");
        System.out.println(RedisDbExecute.queryKeys("haha:*:hehe").size());
        System.out.println();
    }

    public RedisDbExecute() {
    }

    // 获取型如"channelInfo:*:mn"的所有键值
    public static Set<String> queryKeys(String parentKey) {
        TreeSet<String> treeKeys = new TreeSet<>();
        String[] ks = parentKey.split(":");
        ConcurrentHashMap<String, Object> temp = cache;
        for (int i = 0; i < ks.length; i++) {
            if (ks[i].equals("*")) {
                ArrayList<String> list = Collections.list(temp.keys());
                for (int j = 0; j < list.size(); j++) {
                    ConcurrentHashMap<String, Object> zTemp = (ConcurrentHashMap<String, Object>) temp.get(list.get(j));
                    boolean keyExist = true;
                    for (int z = i + 1; z < ks.length; z++) {
                        if (!zTemp.containsKey(ks[z]) && zTemp.get(ks[z]) != null) {
                            keyExist = false;
                            break;
                        }
                        zTemp = (ConcurrentHashMap<String, Object>) zTemp.get(ks[z]);
                    }
                    if (keyExist) {
                        treeKeys.add(parentKey.replace("*", list.get(j)));
                    }
                }
                break;
            }
            else {//找到 *
                if (!temp.containsKey(ks[i])) {
                    break;
                }
                temp = (ConcurrentHashMap<String, Object>) temp.get(ks[i]);
            }
        }
        return treeKeys;
    }

    public static void setString(String key, String value) {
        String[] ks = key.split(":");
        ConcurrentHashMap<String, Object> temp = cache;
        for (int i = 0; i < ks.length; i++) {
            if (!temp.containsKey(ks[i])) {
                temp.put(ks[i], new ConcurrentHashMap<>());
            }
            temp = (ConcurrentHashMap<String, Object>) temp.get(ks[i]);
            if (i == ks.length - 1) {
                temp.put(ks[i], value);
            }
        }
    }

    public static String getString(String key) {
        String[] ks = key.split(":");
        ConcurrentHashMap<String, Object> temp = cache;
        for (int i = 0; i < ks.length; i++) {
            if (!temp.containsKey(ks[i])) {
                return null;
            }
            temp = (ConcurrentHashMap<String, Object>) temp.get(ks[i]);
            if (i == ks.length - 1) {
                return (String) temp.get(ks[i]);
            }
        }
        return null;
    }

    public static void delValue(String key) {
        String[] ks = key.split(":");
        ConcurrentHashMap<String, Object> temp = cache;
        for (int i = 0; i < ks.length; i++) {
            if (!temp.containsKey(ks[i])) {
                return;
            }
            temp = (ConcurrentHashMap<String, Object>) temp.get(ks[i]);
            if (i == ks.length - 1) {
                temp.put(ks[i], null);
            }
        }
    }

    public static Double getDouble(String key) {
        return toDouble(getString(key));
    }

    public static Date getDate(String key, String pattern) {
        return toDate(getString(key), pattern);
    }

    public static Double toDouble(String value) {
        if (value == null) {
            return null;
        }
        else {
            Double doubleValue = null;
            try {
                doubleValue = Double.parseDouble(value);
                return doubleValue;
            }
            catch (Exception var3) {
                return null;
            }
        }
    }

    public static Date toDate(String value, String pattern) {
        if (value == null) {
            return null;
        }
        else {
            SimpleDateFormat sf = null;
            if (pattern == null) {
                sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
            else {
                sf = new SimpleDateFormat(pattern);
            }
            Date dateValue = null;
            try {
                dateValue = sf.parse(value);
            }
            catch (Exception var5) {
                var5.printStackTrace();
            }
            return dateValue;
        }
    }

    public static void deleteKeys(String keyPattern) {
        Set<String> keys = queryKeys(keyPattern);
        if (keys != null) {
            Iterator var3 = keys.iterator();
            while (var3.hasNext()) {
                String key = (String) var3.next();
                delValue(key);
            }
        }
    }
}
